#pragma once

#include<iostream>
#include"Protocol.hpp"

class Calculator
{
public:
    Calculator()
    {}

    Response Execute(const Request &req)
    {
        //已经获得结构化的数据，进行计算
        Response resp;
        switch (req.Oper()) 
        {
            case '+':
                resp.SetResult(req.X() + req.Y());
                break;
            case '-':
                resp.SetResult(req.X() - req.Y());
                break;
            case '*':
                resp.SetResult(req.X() * req.Y());
                break;
            case '/':
                {
                    if(req.Y() == 0)
                    {
                        resp.SetCode(1);//除0错误
                    }
                    else 
                    {
                        resp.SetResult(req.X() / req.Y());
                    }
                }
                break;
            case '%':
                {
                    if(req.Y() == 0)
                    {
                        resp.SetCode(2);//模0错误
                    }
                    else 
                    {
                        resp.SetResult(req.X() % req.Y());
                    }
                }
                break; 
            default:
                resp.SetCode(3);//其他错误
                break;
        }
        return resp;
    }

    ~Calculator()
    {}
 }cal;
 
std::string HanderRequest(std::string &inbuffer)//故意取引用，是协议Decode时拿到完整报文后会移除该报文，进行缓冲区修改
{
    std::string request_str;
    std::string result_str;
    while(Decode(inbuffer, &request_str))
    {
        std::string resp_str;
        //一定拿到完整报文
        //1.反序列化
        if(request_str.empty())
            break;
        Request req;
        if(!req.Deserialize(request_str))
            break;
        std::cout << "#################" << std::endl;
        req.Print();
        std::cout << "#################" << std::endl;

        //2.业务处理
        Response resp = cal.Execute(req);
        //3.序列化
        resp.Serialize(resp_str);
        //4.添加长度说明
        Encode(resp_str);
        //5.添加所有应答
        result_str += resp_str;
    }
    return result_str;
}
